package com.magicalcoder.youyamvc.web.controller.web.school;
import com.magicalcoder.youyamvc.app.school.service.SchoolService;
import com.magicalcoder.youyamvc.app.school.service.SchoolProxyService;
import com.magicalcoder.youyamvc.app.school.constant.SchoolConstant;
import com.magicalcoder.youyamvc.app.school.util.SchoolUtil;
import com.magicalcoder.youyamvc.web.controller.web.school.param.SchoolRequest;
import com.magicalcoder.youyamvc.web.controller.web.school.param.SchoolResponse;
import com.magicalcoder.youyamvc.app.model.School;
import com.magicalcoder.youyamvc.core.common.utils.ProjectUtil;
import com.magicalcoder.youyamvc.core.common.utils.MapUtil;
import com.magicalcoder.youyamvc.core.common.utils.ListUtils;
import com.magicalcoder.youyamvc.core.common.utils.StringUtils;
import com.magicalcoder.youyamvc.core.common.dto.AjaxData;
import com.magicalcoder.youyamvc.core.common.utils.copy.Copyer;
import com.magicalcoder.youyamvc.core.spring.admin.AdminLoginController;
import com.magicalcoder.youyamvc.core.spring.web.WebLoginController;
import com.magicalcoder.youyamvc.web.common.BaseController;
import com.magicalcoder.youyamvc.app.userweb.util.UserWebUtil;
import com.magicalcoder.youyamvc.core.common.exception.BusinessException;

import org.springframework.format.annotation.DateTimeFormat;
import java.util.*;
import java.math.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;

/**
* 代码为自动生成 Created by www.magicalcoder.com
* 如果你改变了此类 read 请将此行删除
* 欢迎加入官方QQ群:323237052
*/

@RequestMapping({"/user/school"})
@Controller
public class SchoolUserController extends WebLoginController
{

    @Resource
    private SchoolService schoolService;
    @Resource
    private SchoolProxyService schoolProxyService;
    /** method:GET
    *   url:/user/school/list/{pageIndex}/{pageSize}?...
    *   demo:/user/school/list/1/20
    *   获取学校分页数据
    *   是否需要登录                          是
    *是否必须   入参                          注释
    *  是   @pageIndex                     (Integer)当前页码 [1,n]
    *  是   @pageSize                      (Integer)每页条数 [1,n]
    *  否   @callback                      (String)回调方法
    *  否   @orderBySqlField               (String)排序字段
    *  否   @descAsc                       (String)desc|asc
    *  否   @encode                        (String)编码 默认UTF-8
    *  否   @id                     (Long)学校主键 
    *  否   @schoolName                     (String)学校名称 
    *  否   @headImg                     (String)学校头像 
    *  否   @classCount                     (Integer)班级个数 
    *  否   @adress                     (String)学校地址 
    *  否   @schoolType                     (Integer)学校类型 [{"":"全部"},
{"0":"普通"},
{"1":"重点"}]
    *  否   @open                     (Boolean)是否开学 [{"":"全部"},{"false":"否"},{"true":"是"}]
    *  否   @createTime                     (Date)创建时间 
    *  否   @schoolDesc                     (String)学校描述 
    *  否   @updateTime                     (Date)更新时间 
    *  否  like @schoolNameFirst                     (String)学校名称 
    *  否  in @schoolTypeFirst                     (Integer)学校类型 [{"":"全部"},
{"0":"普通"},
{"1":"重点"}]
    *  否  >= @createTimeFirst                     (Date)创建时间 
    *  否  <= @createTimeSecond                  (Date)创建时间 
    *  返回
    *   {
    *      code:0,message:"",jsonp:"",
    *      info:
                [{
    *              id         (Long)学校主键 
    *              schoolName         (String)学校名称 
    *              headImg         (String)学校头像 
    *              classCount         (Integer)班级个数 
    *              adress         (String)学校地址 
    *              schoolType         (Integer)学校类型 [{"":"全部"},
{"0":"普通"},
{"1":"重点"}]
    *              open         (Boolean)是否开学 [{"":"全部"},{"false":"否"},{"true":"是"}]
    *              createTime         (Date)创建时间 
    *              schoolDesc         (String)学校描述 
    *              updateTime         (Date)更新时间 
    *      }]
    *   }
    */
    @RequestMapping(value={"list/{pageIndex}/{pageSize}"}, method={RequestMethod.GET})
    public void list(@PathVariable Integer pageIndex,@PathVariable Integer pageSize,
        @RequestParam(required=false, value="orderBySqlField") String orderBySqlField,
        @RequestParam(required=false, value="descAsc") String descAsc,
        @RequestParam(required=false, value="callback") String callback,
        @RequestParam(required=false, value="encode") String encode,
        @RequestParam(required = false,value ="id")   Long id,
        @RequestParam(required = false,value ="schoolName")   String schoolName,
        @RequestParam(required = false,value ="headImg")   String headImg,
        @RequestParam(required = false,value ="classCount")   Integer classCount,
        @RequestParam(required = false,value ="adress")   String adress,
        @RequestParam(required = false,value ="schoolType")   Integer schoolType,
        @RequestParam(required = false,value ="open")   Boolean open,
        @RequestParam(required = false,value ="createTime")      @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date createTime,
        @RequestParam(required = false,value ="schoolDesc")   String schoolDesc,
        @RequestParam(required = false,value ="updateTime")      @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date updateTime,
        @RequestParam(required = false,value ="schoolNameFirst")                            String schoolNameFirst ,
        @RequestParam(required = false,value ="schoolTypeFirst")                            String schoolTypeFirst ,
        @RequestParam(required = false,value ="createTimeFirst")                    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date createTimeFirst ,
        @RequestParam(required = false,value ="createTimeSecond")                    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date createTimeSecond ,
        HttpServletRequest request,HttpServletResponse response,ModelMap modelMap)
    {
        try{
            String orderBySqlFieldStr = ",id,school_name,head_img,class_count,adress,school_type,open,create_time,school_desc,update_time,";
            String orderBy = ProjectUtil.filterOrderBy(orderBySqlFieldStr,orderBySqlField,descAsc);
            if(StringUtils.isBlank(orderBy)){
                orderBy = "create_time desc";
            }
            pageSize = Math.min(SchoolConstant.PAGE_MAX_SIZE,pageSize);
            int idx = (pageIndex.intValue() - 1) * pageSize;
            Long _userId = UserWebUtil.userId(request);
            Map<String,Object> query = MapUtil.buildMap("orderBy", orderBy,
         "id",id,
         "schoolName",schoolName,
         "headImg",headImg,
         "classCount",classCount,
         "adress",adress,
         "schoolType",schoolType,
         "open",open,
         "createTime",createTime,
         "schoolDesc",schoolDesc,
         "updateTime",updateTime,
                    "schoolNameFirst",schoolNameFirst ,
                    "schoolTypeFirst",ProjectUtil.toList(schoolTypeFirst ,Integer.class),
                    "createTimeFirst",createTimeFirst ,
                    "createTimeSecond",createTimeSecond ,
                "start",idx,"limit", pageSize ,"userId",_userId);

            List<School> pageList = this.schoolService.getSchoolList(query);
            toWebSuccessJson(callback,encode,response, coverToResponseList(pageList));
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }

    private List<SchoolResponse> coverToResponseList(List<School> pageList){
        if(ListUtils.isBlank(pageList)){
            return null;
        }
        return Copyer.copy(pageList,SchoolResponse.class);
    }


    /** method:GET
    *   url:/user/school/item?...
    *   demo:/user/school/item
    *   获取学校详情数据
    *   是否需要登录                          是
    *是否必须   入参                          注释
    *  否   @callback                      (String)回调方法
    *  否   @encode                        (String)编码 默认UTF-8
     *  否  @id        (Long) 主键
    *  返回
    *   {
    *      code:0,message:"",jsonp:"",
    *      info:
                {
    *              id         (Long)学校主键 
    *              schoolName         (String)学校名称 
    *              headImg         (String)学校头像 
    *              classCount         (Integer)班级个数 
    *              adress         (String)学校地址 
    *              schoolType         (Integer)学校类型 [{"":"全部"},
{"0":"普通"},
{"1":"重点"}]
    *              open         (Boolean)是否开学 [{"":"全部"},{"false":"否"},{"true":"是"}]
    *              createTime         (Date)创建时间 
    *              schoolDesc         (String)学校描述 
    *              updateTime         (Date)更新时间 
    *      }
    *   }
    */
    @RequestMapping(value={"item"}, method={RequestMethod.GET})
    public void item(
        @RequestParam(required=false, value="callback") String callback,
        @RequestParam(required=false, value="encode") String encode,
        @RequestParam(required = false,value ="id")Long id,
        HttpServletRequest request,HttpServletResponse response,ModelMap modelMap)
    {
        try{
            Long _userId = UserWebUtil.userId(request);
            Map<String,Object> query = MapUtil.buildMap(
                     "id",id,
                "userId",_userId
            );
            School school = this.schoolService.selectFirstSchool(query);
            toWebSuccessJson(callback,encode,response, Copyer.copy(school,new SchoolResponse()));
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }

    /** method:post
    *   url:/user/school/save?...
    *   demo:/user/school/save?...
    *   保存学校
    *   是否需要登录               是
    *是否必须         入参         注释
    * 否id (Long)学校主键  为空表示插入否则表示更新
    * 否schoolName (String)学校名称  
    * 否headImg (String)学校头像  
    * 否classCount (Integer)班级个数  
    * 否adress (String)学校地址  
    * 否schoolType (Integer)学校类型 [{"":"全部"},
{"0":"普通"},
{"1":"重点"}] 
    * 否open (Boolean)是否开学 [{"":"全部"},{"false":"否"},{"true":"是"}] 
    * 否createTime (Date)创建时间  
    * 否schoolDesc (String)学校描述  
    * 否updateTime (Date)更新时间  
    *
    *   返回
    *   {
    *      code:0,message:"",jsonp:"",
    *      info:id 主键 Long
    *   }
    */
    @RequestMapping(value={"save"}  ,method={RequestMethod.POST})
    public void save(@ModelAttribute SchoolRequest schoolRequest,

        @RequestParam(required=false, value="callback") String callback,
        @RequestParam(required=false, value="encode") String encode,
        HttpServletRequest request,HttpServletResponse response) {
        Long _userId = UserWebUtil.userId(request);
        try{
            Long id = saveEntity(_userId,schoolRequest);
            toWebSuccessJson(callback,encode,response, id);
        }catch (BusinessException e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(callback,encode,response,e.getErrorCode(), exceptionMsg);
            e.printStackTrace();
        }
        catch (Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(callback,encode,response, exceptionMsg);
            e.printStackTrace();
        }
    }

    private Long saveEntity(Long userId,SchoolRequest schoolRequest){
        if (schoolRequest.getId() == null) {
            School school = new School();
            Copyer.copy(schoolRequest,school);
            school.setCreateTime(new Date());
            return this.schoolService.insertSchool(school);
        } else {
            School entity = getEntity(userId,schoolRequest.getId());
            if(entity!=null){
                Copyer.reflectCopyZeroNotNull(schoolRequest, entity);
                entity.setUpdateTime(new Date());
                this.schoolService.updateSchool(entity);
            }
        }
        return schoolRequest.getId();
    }

    private School getEntity(Long userId,Long id){
        return this.schoolService.selectOneSchoolWillThrowException(ProjectUtil.buildMap(
            "id",id));
    }

    /** method:get
    *   url:/user/school/delete?...
    *   demo:/user/school/delete?...

    *   删除学校
    *   是否需要登录                          是
    *是否必须   入参                          注释
    *  否   @callback                      (String)回调方法
    *  否   @encode                        (String)编码 默认UTF-8
    *  否  @id        (Long) 主键
    *   返回
    *   {
    *      code:0,message:"",jsonp:"",
    *      info:true||false
    *   }
    */
    @RequestMapping(value={"delete"}, method={RequestMethod.GET})
    public void delete(
        @RequestParam(required=false, value="callback") String callback,
        @RequestParam(required=false, value="encode") String encode,
        @RequestParam(required = false,value ="id")Long id,
    HttpServletRequest request,HttpServletResponse response)
    {
        try{
            Long _userId = UserWebUtil.userId(request);
            Map<String,Object> query = MapUtil.buildMap(
            "id",id,
            "userId",_userId
            );
            this.schoolService.deleteSchoolList(query);
            toWebSuccessJson(callback,encode,response, true);
        }catch(Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,exceptionMsg);
        }
    }



}